﻿using System;
using System.IO;
using System.Windows.Markup;
using DyUi.Base.Constants;
using DyUi.Base.Interfaces;
using DyUi.Base.Interfaces.SubSystems;

namespace DyUi.Core.SubSystems
{
    public class ControlSubSystem : DyUiControllerSubSystem, IControlSubSystem
    {
        public IDyUiControl RootControl { get; set; }

        public virtual IDyUiControl CreateControl(String controlPath)
        {
            var controlName = new DirectoryInfo(controlPath).Name.Replace(".dyui", String.Empty);

            var xamlPath = Path.Combine(controlPath, String.Format("{0}.xaml", controlName));

            if (File.Exists(xamlPath))
            {
                var control = XamlReader.Load(File.OpenRead(xamlPath)) as IDyUiControl;
                control.DyUiName = controlName;
                control.Path = new DirectoryInfo(controlPath);
                control.ServiceLocator = Controller.ServiceSubSystem.LoadServiceLocator(control);

                return control;
            }

            return null;
        }

        public virtual IDyUiControl CreateControlByName(String name)
        {
            var paths = (Controller.SettingsSubSystem[SettingsKeys.ControlSearchPaths] ?? String.Empty).Split(',');

            foreach (var path in paths)
            {
                var controlPath = Path.Combine(path, name + General.DyUiExtension);

                if (Directory.Exists(controlPath))
                    return Controller.ControlSubSystem.CreateControl(controlPath);
            }

            return null;
        }
    }
}
